package org.djw.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.djw.basic.constant.BaseConstants;
import org.djw.basic.exception.BusinessException;
import org.djw.basic.util.AjaxResult;
import org.djw.basic.util.HttpClientUtils;
import org.djw.basic.util.MD5Utils;
import org.djw.basic.util.StrUtils;
import org.djw.user.domain.Logininfo;
import org.djw.user.domain.User;
import org.djw.user.domain.WxUser;
import org.djw.user.dto.LoginDto;
import org.djw.user.mapper.LogininfoMapper;
import org.djw.user.mapper.UserMapper;
import org.djw.user.mapper.WxUserMapper;
import org.djw.user.service.ILoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 账号密码登录
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //验证type,判断是用户还是员工
        if (loginDto.getType() == null){
            throw new BusinessException("type不能为空");
        }
        //查询用户判断是否存在
        Logininfo logininfo = logininfoMapper.loadByUsername(loginDto);
        if (logininfo == null){
            throw new BusinessException("用户不存在,请重新输入!");
        }
        //如果用户名正确,查询密码是否正确
        //获取用户保存的盐值,使用loginDto的密码加密和保存的密码进行比对
        String passwordTmp = MD5Utils.encrypByMd5(loginDto.getPassword() + logininfo.getSalt());
        if (!passwordTmp.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误,请检查密码");
        }
        //调用免密登录方法,返回map
        return login(logininfo);
    }

    /**
     * 微信登录
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechat(String code) {
        //空校验
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数不能为空");
        }
        //根据code获取token 和 openid
        String tokenUrl = BaseConstants.GET_TOKEN_URL
                .replace("APPID", BaseConstants.APPID)
                .replace("SECRET", BaseConstants.SECRET)
                .replace("CODE", code);
        //调用微信返回token和openid
        String tokenObjStr = HttpClientUtils.httpGet(tokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(tokenObjStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //根据openid查询wxUser
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        //如果不为空,就说明不是第一次扫码
        if (wxUser != null){
            //直接免密登录
            Logininfo logininfo = logininfoMapper.loadByUserId(wxUser.getUser_id());
            Map<String, Object> map = login(logininfo);
            return AjaxResult.me().setResultObj(map);
        }else {
            String binderParams = "?accessToken=" + accessToken + "&openId=" + openId;
            return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
        }

    }

    /**
     * 微信绑定
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> binderWechat(Map<String, String> params) {
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        //空校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode) ||
                StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数不能为空");
        }
        //校验验证码
        Object codeTmp = redisTemplate.opsForValue().get(BaseConstants.BUSINESS_BINDER_PREFIX + phone);
        if (codeTmp == null){
            throw new BusinessException("验证码已经过期,请重新获取!");
        }
        //验证验证码是否正确  equalsIgnoreCase不区分大小写进行值比对
        String code = ((String) codeTmp).split(":")[0];
        if (!code.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("验证码错误!");
        }
        //根据phone查询是否被注册
        User user = userMapper.loadByphone(phone);
        Logininfo logininfo = null;
        if ( user != null){
            //user不为空说明已经被注册
            logininfo = logininfoMapper.loadById(user.getLogininfo_id());
        }else {
            //要直接生成新的
            user = initUser(phone);
            logininfo = user2Logininfo(user);
            // 1.保存logininfo
            logininfoMapper.save(logininfo);//返回自增id
            // 2.保存 user
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }
        //保存过后调用微信查询用户的基本信息,进行wxUser的保存
        String getWxUserURL = BaseConstants.GET_WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //调用微信查询
        String wxUserStr = HttpClientUtils.httpGet(getWxUserURL);
        WxUser wxUser = JSONObject.parseObject(wxUserStr, WxUser.class);
        //进行绑定
        wxUser.setUser_id(user.getId());
        wxUserMapper.save(wxUser);
        //免密登录
        return login(logininfo);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //拷贝logininfo
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
    private User initUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setUsername(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //使用盐值加密
        String md5Pwd = MD5Utils.encrypByMd5("1" + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    /**
     * 免密登录
     * @param logininfo
     * @return
     */
    private Map<String, Object> login(Logininfo logininfo){
        //登录成功,保存token到redis
        String token = UUID.randomUUID().toString();//必须加toString
        //保存redis
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES);
        //返回登录成功的信息
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        //将隐私信息设置为空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);
        return map;
    }
}